<template>
  <div class="agent__container">
    <div class="agent__body">
      <!-- 头部 -->
      <agent-header @search="handleSearch" :search-text="agentStore.searchKeyword" />
      <!-- 分类 -->
      <div v-show="!agentStore.searchKeyword" class="agent__categories mb-10" :class="{ 'isExpanded': isExpanded }">
        <div ref="parent" class="category__list" :style="positionStyle">
          <el-button
            v-for="item in agentStore.catgories"
            :key="item.id"
            class="fs-12"
            @click="handleClickItem(item)"
            :type="agentStore.active === item.id ? 'primary' : 'default'"
            >{{ item.name }}</el-button
          >
        </div>
        <div v-if="maxHeight > 68" class="load-more">
          <span @click="toggle"><svg-icon icon-class="left-btn" class="fs-16"></svg-icon></span>
        </div>
      </div>
      <!-- 智能体列表 -->
      <div
        ref="agentList"
        class="list__wrapper"
        :class="{ 'list_isExpanded': isExpanded }"
        :style="`height: calc(100vh - ${(!agentStore.searchKeyword ? parentHeight : 0)}px);`"
        v-loading="listLoading"
        v-infinite-scroll="() => getAgentList()"
        :infinite-scroll-disabled="disabled"
        :infinite-scroll-distance="40"
      >
        <agent-list :list="agentStore.list" />
        <div
          class="list__empty"
          v-show="!listLoading && agentStore.list.length === 0">
          <p class="fs-12 fs-c-7" v-if="agentStore.active === 'Favorite'">
            暂无收藏记录
          </p>
          <p class="fs-12 fs-c-7" v-else-if="agentStore.searchKeyword">无相关内容</p>
          <p class="fs-12 fs-c-7" v-else>该列表暂无数据</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import AgentHeader from './header.vue'
import AgentList from './list.vue'
import { getAgentCatgoriesApi, getAgentListApi } from '@/api/agent'

export default {
  name: 'Agent',
  inject: ['detectIsLogin'],
  components: {
    AgentHeader,
    AgentList
  },
  data () {
    return {
      isExpanded: false,
      maxHeight: 68,
      parentHeight: 68,
      curPage: 1,
      pageSize: 20,
      isEnd: false,
      listLoading: false
    }
  },
  computed: {
    ...mapGetters(['agentStore']),
    positionStyle () {
      return {
        'max-height': `${this.isExpanded ? this.maxHeight : 68}px`
      }
    },
    disabled () {
      return this.listLoading || this.isEnd
    }
  },
  watch: {
    'agentStore.isShow' (val) {
      if (val) {
        this.$xz('HtmlClickReport', { ReportID: 7619 })
        this.getCategories()
        this.getAgentList(1)
        // window.onresize = () => {
        //   this.windowOnresize()
        // }
      } else {
        window.onresize = null
      }
    }
  },
  mounted () {
    this.getCategories()
    this.getAgentList(1)
    // this.handleResize()
  },
  methods: {
    windowOnresize () {
      return this.$nextTick(() => {
        const parent = this.$refs.parent
        const lastChild = parent?.lastElementChild
        if (lastChild) {
          this.maxHeight = lastChild.offsetTop - parent.offsetTop + lastChild.offsetHeight
        }
      }, 100)
    },
    handleResize () {
      this.$nextTick(() => {
        const resizeObserver = new ResizeObserver(entries => {
          for (const entry of entries) {
            const { height } = entry.contentRect
            this.parentHeight = height
          }
        })
        resizeObserver.observe(this.$refs.parent)
      })
    },
    toggle () {
      this.isExpanded = !this.isExpanded
    },
    handleClickItem (item) {
      if (item.id === 'Favorite' && !this.detectIsLogin()) {
        return
      }
      if (item.id === this.agentStore.active) return
      this.$store.dispatch('agent/setActiveTab', item.id)
      this.getAgentList(1)
    },

    async getCategories () {
      const params = { page: 1, page_size: 40, parent_category_id: 0 }
      const { data } = await getAgentCatgoriesApi(params)
      const list = data?.data.list || []
      const defaultCategorys = [
        { id: 'Favorite', name: '收藏' },
        { id: 'All', name: '全部' }
      ]
      this.$store.dispatch('agent/updateCatgoeries', { list: [...defaultCategorys, ...list], reset: true })
      this.windowOnresize()
    },

    handleSearch (value) {
      this.$store.dispatch('agent/updateSearchKeyword', value)
      this.$xz('HtmlClickReport', { ReportID: 7622 })
      this.getAgentList(1)
    },

    async getAgentList (pageIndex) {
      const page = pageIndex || this.curPage + 1
      if (page === 1) {
        this.$refs.agentList && (this.$refs.agentList.scrollTop = 0)
        this.isEnd = false
      }
      if (this.disabled) return

      const isStar = this.agentStore.active === 'Favorite'
      let category_id = null
      if (!['Favorite', 'All'].includes(this.agentStore.active) && !this.agentStore.searchKeyword) { category_id = this.agentStore.active }

      this.listLoading = true
      const { data: subCategories } = await getAgentCatgoriesApi({
        page: 1,
        page_size: 40,
        parent_category_id: category_id
      })
      const subs = (subCategories?.data.list || []).map((v) => v.id)
      if (category_id) subs.unshift(category_id)

      const params = {
        page,
        page_size: this.pageSize,
        is_star: isStar,
        keyword: this.agentStore.searchKeyword,
        category_ids: subs.join(',')
      }
      const { data } = await getAgentListApi(params)
      const list = data?.data.list || []
      if (list.length === 0 && this.agentStore.searchKeyword && page === 1) {
        this.$xz('HtmlClickReport', { ReportID: 7623 })
      }
      this.listLoading = false
      this.isEnd = list.length < this.pageSize
      if (list.length) this.curPage = page
      this.$store.dispatch('agent/updateList', { list, force: page === 1 })
    }
  }
}
</script>

<style lang="scss" scoped>
.agent__container {
  padding: 0 20px 20px 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  height: 100%;
}
.agent__body {
  overflow: hidden;
  display: flex;
  line-height: 1;
  flex-direction: column;
}
.list__wrapper {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 4px;
  // transition: height 0.3s;
}
.list__empty {
  padding: 40px;
  display: flex;
  line-height: 1;
  justify-content: center;
}

.agent__categories {
  position: relative;
  padding: 0 4px;
  .category__list {
    transition: max-height 0.3s;
    padding-right: 24px;
    overflow: hidden;
    position: relative;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    .el-button {
      line-height: 16px;
      padding: 6px 14px;
      margin-left: 0;
      height: 28px;
      border: 0;
      font-size: $font-size-base;
      color: rgba($color: #fff, $alpha: 0.7);
      &:hover {
        color: #ffffff;
        background: rgba(255,255,255,0.2);
      }
      &.el-button--primary {
        color: #ffffff;
        &:hover {
          background-color: #4E5FFF;
        }
      }
    }
  }
  .load-more {
    display: flex;
    position: absolute;
    bottom: 2px;
    right: 0;
    span {
      display: flex;
      width: 28px;
      height: 28px;
      background: rgba(255,255,255,0.1);
      border-radius: 5px;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: rgba($color: #fff, $alpha: 0.7);
      &:hover {
        background: rgba(255,255,255,0.2);
        color: #FFF;
      }
    }
    .svg-icon {
      transform: rotate(-90deg);
    }
  }
  &.isExpanded {
    .load-more .svg-icon {
      transform: rotate(90deg);
    }
  }
}
</style>
